import React, {useEffect, useState} from 'react';
import store from "../store";
import {changeNum} from "../store/slice/cart";

function CartList(props) {
    const [cartList,setCartList] = useState(store.getState().cart.cartList)
    useEffect(()=>{
        const unsubscribe = store.subscribe(()=>{
            setCartList(store.getState().cart.cartList)
        })
        return ()=>{
            unsubscribe()
        }
    },[])
    return (
        <div>
            {
                !cartList.length? <h3>暂无商品</h3>:cartList.map(item=>(
                    <div key={item.id}>
                        <p>商品名称：{item.goodsName}</p>
                        <p>商品价格：￥{item.goodsPrice.toFixed(2)}</p>
                        <p>商品个数：<button onClick={()=>{
                            store.dispatch(changeNum({id:item.id,num:-1}))
                        }}>-</button>{item.buyNum}<button onClick={()=>{
                            store.dispatch(changeNum({id:item.id,num:1}))
                        }}>+</button></p>
                        <p>小计：￥{(item.goodsPrice*item.buyNum).toFixed(2)}</p>
                        <hr/>
                    </div>
                ))
            }
        </div>
    );
}

export default CartList;